<?php

namespace app\comms\controller;

use app\common\controller\Sms;
use app\common\lib\Netease as ease;
use app\common\lib\redis\Redis;
use app\common\lib\SmsRedis;
use app\common\lib\Util;
use app\common\model\User as UserModel;
use app\common\model\User;
use app\common\model\UserProfile as ProfileModel;
use app\common\model\UserToken as TokenModel;
use app\common\validate\LoginOrRegister as validate;
use think\Controller;
use think\facade\Log;
use think\Request;

class Common extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->cors();
    }
    //跨域
    public function cors(){
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
    }
    //发送短信
    public function sendSms(Request $request){
        $route = $request->routeInfo()['rule'];
        $phoneNum = $request->phone_num;
        Sms::sendSms($phoneNum,$route);
    }
    /* 登录或者注册 */
    public function loginOrRegister(Request $request, ease $ease, UserModel $userModel, TokenModel $tokenModel)
    {
        $phoneNum = $request->phone_num;
        $validate = new validate();
        if (!$validate->check(['phone_num' => $phoneNum])) {
            return Util::apiResponse([], $validate->getError(), 400);
        }
        $userExist = $userModel->where(['phone_num' => $phoneNum,'is_user'=>1])->field('id,accid,phone_num')->find();
        $redis = Redis::getInstance();
        $code = $request->code;
        $token = $this->setAppLoginToken($phoneNum);
        //登录
        if ($userExist) {
            $sentCode = $redis->get(SmsRedis::loginSmsKey($phoneNum));
            if (!$code || !$sentCode || $code != $sentCode) {
                return Util::apiResponse([], '验证码错误', 400);
            }
            $user_token = $tokenModel->where(['user_id' => $userExist['id']])->field('token,token_expire_time')->find();
            // 过期
            if ($user_token && time() > $user_token['token_expire_time']) {
                $tokenModel->save(['token' => $token, 'token_expire_time' => time() + 86400 * 30], ['user_id' => $userExist['id']]);
            }
            if (!$user_token) {
                $tokenModel->saveToken($userExist['id'], $token);
            } else {
                $token = $user_token['token'];
            }
            $user = $userExist;
        } else {
            //注册
            $sentCode = $redis->get(SmsRedis::regSmsKey($phoneNum));
            if (!$code || !$sentCode || $code != $sentCode) {
                return Util::apiResponse([], '验证码错误', 400);
            }
            try{
                $accid = UserModel::getAccid();
                $meId = UserModel::getMeid();
            }catch (\Exception $e){
                $userModel->rollback();
                return Util::apiResponse([], $e->getMessage(), 400);
            }
            $userData = [
                'phone_num' => $phoneNum,
                'accid'=>$accid,
                'me_id'=>$meId,
                'is_user' => 1
            ];
            //开启事务
            $userModel->startTrans();
            $regResult = $userModel->save($userData);
            if (!$regResult) {
                $userModel->rollback();
                return Util::apiResponse([], '注册失败', 400);
            }
            //网易云信注册
            $data = [
                'accid' => $accid,
                'name'=>User::createNickname(),
                'mobile'=>$phoneNum,
                //'token'=>$token,
                'ex'=>array('me_id'=>$meId)
            ];
            $result = $ease->createUser($data);
            if ($result['error'] == 1) {
                $userModel->rollback();
                return Util::apiResponse([], $result['message'], 400);
            }
            $token = $result['token'];
            $userModel->commit();
            $userId = $userModel->id;
            $user = $userModel->field('id,phone_num,accid')->where(['id' => $userId,'is_user'=>1])->find();
            // 添加记录user_token
            $tokenModel->saveToken($userId, $token);
        }
        return Util::apiResponse(['token' => $token,'user_id'=>$user['id'],'accid'=>$user['accid']], '登录成功', 200);
    }
    //设置登录token
    public function setAppLoginToken($phone)
    {
        $str = md5(uniqid(md5(microtime(true)), true));
        $str = sha1($str . $phone);
        return $str;
    }

}
